package net.youpo.Market.UI.Manager;

import java.util.HashMap;
import java.util.Map;

import net.youpo.Market.BaseActivity;
import net.youpo.Market.R;
import net.youpo.Market.Download.Downloads;
import net.youpo.Market.Util.DeviceInfo;
import net.youpo.Market.Util.GlobalVariables;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;

public class DownloadManagerActivity extends BaseActivity {
    private ExpandableListView mListView;
    private Cursor mDownloadCursor, mDownloadFinishCursor;
    private DownloadManagerAdapter mAdapter;
    private int mStatusColumnId;
    private int mIdColumnId;
    protected Map<Integer, Cursor> cursorMap = new HashMap<Integer, Cursor>();
    Button startAllBtn;
    private PackageReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.appdownload_layout);
        mListView = (ExpandableListView) findViewById(R.id.list);
        mListView.setEmptyView(findViewById(R.id.empty));
        mDownloadCursor = managedQuery(
                Downloads.Impl.CONTENT_URI,
                new String[] { Downloads.Impl._ID, Downloads.Impl.COLUMN_TITLE,
                        Downloads.Impl.COLUMN_STATUS,
                        Downloads.Impl.COLUMN_TOTAL_BYTES,
                        Downloads.Impl.COLUMN_CURRENT_BYTES,
                        Downloads.Impl.COLUMN_DESCRIPTION,
                        Downloads.Impl.COLUMN_APP_ID,
                        Downloads.Impl.COLUMN_ICON_URL,
                        Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
                        Downloads.Impl.COLUMN_LAST_MODIFICATION,
                        Downloads.Impl.COLUMN_VISIBILITY, Downloads.Impl._DATA,
                        Downloads.Impl.COLUMN_MIME_TYPE,
                        Downloads.Impl.COLUMN_CONTROL },
                Downloads.Impl.COLUMN_STATUS + " != ?  AND "
                        + Downloads.Impl.COLUMN_DOWNLOAD_TYPE + " = ?",
                new String[] { String.valueOf(Downloads.STATUS_SUCCESS),
                        String.valueOf(Downloads.TYPE_DOWNLOAD) },
                Downloads.Impl._ID);
        mDownloadFinishCursor = managedQuery(
                Downloads.Impl.CONTENT_URI,
                new String[] { Downloads.Impl._ID, Downloads.Impl.COLUMN_TITLE,
                        Downloads.Impl.COLUMN_STATUS,
                        Downloads.Impl.COLUMN_TOTAL_BYTES,
                        Downloads.Impl.COLUMN_CURRENT_BYTES,
                        Downloads.Impl.COLUMN_DESCRIPTION,
                        Downloads.Impl.COLUMN_APP_ID,
                        Downloads.Impl.COLUMN_ICON_URL,
                        Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
                        Downloads.Impl.COLUMN_LAST_MODIFICATION,
                        Downloads.Impl.COLUMN_VISIBILITY, Downloads.Impl._DATA,
                        Downloads.Impl.COLUMN_MIME_TYPE,
                        Downloads.Impl.COLUMN_CONTROL },
                Downloads.Impl.COLUMN_STATUS + " = ?  AND "
                        + Downloads.Impl.COLUMN_DOWNLOAD_TYPE + " = ?",
                new String[] { String.valueOf(Downloads.STATUS_SUCCESS),
                        String.valueOf(Downloads.TYPE_DOWNLOAD) },
                Downloads.Impl._ID);
        cursorMap.put(DownloadManagerAdapter.GROUP_ID_DOWNLOAD_UNFINISHED,
                mDownloadCursor);
        cursorMap.put(DownloadManagerAdapter.GROUP_ID_DOWNLOAD_FINISHED,
                mDownloadFinishCursor);
        mAdapter = new DownloadManagerAdapter(this, cursorMap);
        mListView.setAdapter(mAdapter);
        mListView.setGroupIndicator(null);
        mListView
                .expandGroup(DownloadManagerAdapter.GROUP_ID_DOWNLOAD_UNFINISHED);
        mListView
                .expandGroup(DownloadManagerAdapter.GROUP_ID_DOWNLOAD_FINISHED);
        startAllBtn = (Button) findViewById(R.id.start_all_btn);
        startAllBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startAllDownloads();
            }
        });
        registerReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAdapter.registerContentObserver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAdapter.unregisterContentObserver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    /**
     * Cancel all downloads. As canceled downloads are not listed, we removed
     * them from the db. Removing a download record, cancels the download.
     */
    private void cancelAllDownloads() {
        if (mDownloadCursor.moveToFirst()) {
            StringBuilder where = new StringBuilder();
            boolean firstTime = true;
            while (!mDownloadCursor.isAfterLast()) {
                int status = mDownloadCursor.getInt(mStatusColumnId);
                if (!Downloads.Impl.isStatusCompleted(status)) {
                    if (firstTime) {
                        firstTime = false;
                    } else {
                        where.append(" OR ");
                    }
                    where.append("( ");
                    where.append(Downloads.Impl._ID);
                    where.append(" = '");
                    where.append(mDownloadCursor.getLong(mIdColumnId));
                    where.append("' )");
                }
                mDownloadCursor.moveToNext();
            }
            if (!firstTime) {
                getContentResolver().delete(Downloads.Impl.CONTENT_URI,
                        where.toString(), null);
            }
        }
    }

    private void startAllDownloads() {
        if (mDownloadCursor.moveToFirst()) {
            StringBuilder where = new StringBuilder();
            boolean firstTime = true;
            while (!mDownloadCursor.isAfterLast()) {
                int status = mDownloadCursor.getInt(mStatusColumnId);
                if (!Downloads.Impl.isStatusCompleted(status)) {
                    if (firstTime) {
                        firstTime = false;
                    } else {
                        where.append(" OR ");
                    }
                    where.append("( ");
                    where.append(Downloads.Impl._ID);
                    where.append(" = '");
                    where.append(mDownloadCursor.getLong(mIdColumnId));
                    where.append("' )");
                }
                mDownloadCursor.moveToNext();
            }
            if (!firstTime) {
                ContentValues values = new ContentValues();
                values.put(Downloads.Impl.COLUMN_CONTROL,
                        Downloads.Impl.CONTROL_RUN);
                getContentResolver().update(Downloads.Impl.CONTENT_URI, values,
                        where.toString(), null);
            }
        }
    }

    public class PackageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 接收广播：设备上删除了一个应用程序包。
            if (intent.getAction()
                    .equals("android.intent.action.PACKAGE_ADDED")
                    || intent.getAction().equals(
                            "android.intent.action.PACKAGE_REPLACED")) {
                String packageName = intent.getDataString();
                packageName = packageName.replace("package:", "");
                Log.e("add", "安装了:" + packageName + "包名的程序");
                String where = Downloads.Impl.COLUMN_PACKAGE_NAME + " = ? AND "
                        + Downloads.Impl.COLUMN_STATUS + " = ? AND "
                        + Downloads.Impl.COLUMN_DOWNLOAD_TYPE + " = ?";
                getContentResolver().delete(
                        Downloads.Impl.CONTENT_URI,
                        where,
                        new String[] { packageName,
                                String.valueOf(Downloads.STATUS_SUCCESS),
                                String.valueOf(Downloads.TYPE_DOWNLOAD) });
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DownloadManagerActivity.this
                                .runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        GlobalVariables.ALL_INSTALL_APP.clear();
                                        GlobalVariables.ALL_INSTALL_APP = DeviceInfo
                                                .getInstallAppInfo();
                                        mAdapter.refreshData();
                                        mListView
                                                .collapseGroup(DownloadManagerAdapter.GROUP_ID_DOWNLOAD_FINISHED);
                                        mListView
                                                .expandGroup(DownloadManagerAdapter.GROUP_ID_DOWNLOAD_FINISHED);
                                    }
                                });
                    }
                }).start();
            }

        }
    }

    private void registerReceiver() {
        mReceiver = new PackageReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.PACKAGE_REPLACED");
        intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
        intentFilter.addDataScheme("package");
        registerReceiver(mReceiver, intentFilter);
    }
}